package com.cmy.framework_network.base

import com.cmy.framework_network.apiresponse.MoshiResultTypeAdapterFactory
import com.cmy.framework_network.apiresponse.NetworkResponseAdapterFactory
import com.cmy.framework_network.commoninterceptor.CommonRequestInterceptor
import com.cmy.framework_network.commoninterceptor.CommonResponseInterceptor
import com.cmy.framework_network.environment.EnvironmentActivity
import com.cmy.framework_network.environment.IEnvironment
import com.cmy.framework_network.error.GlobalErrorHandler
import com.cmy.framework_network.utils.SSLSocketClient
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory

abstract class BaseNetworkApi  : IEnvironment {

    var mRetrofit: Retrofit
    private var mBaseUrl: String get() = if(mIsFormal) getTest() else getFormal()
        set(value) = TODO()
    private val globalErrorHandler = GlobalErrorHandler()

    companion object {
        private var iNetworkRequiredInfo: INetworkRequiredInfo? = null
        private var mIsFormal = true

        fun init(networkRequiredInfo: INetworkRequiredInfo) {
            iNetworkRequiredInfo = networkRequiredInfo
            mIsFormal = false
            networkRequiredInfo.getApplicationContext()?.let { mIsFormal = EnvironmentActivity.isOfficialEnvironment(it) }
        }
    }

    constructor() {
        val retrofitBuilder = Retrofit.Builder()
        retrofitBuilder.baseUrl(mBaseUrl)
        retrofitBuilder.client(getOkHttpClient())
        retrofitBuilder.addConverterFactory(MoshiConverterFactory.create(moshi))
        retrofitBuilder.addCallAdapterFactory(
            NetworkResponseAdapterFactory(globalErrorHandler)
        )
        retrofitBuilder.client(getOkHttpClient())
        mRetrofit = retrofitBuilder.build()
    }

    private val moshi = Moshi.Builder()
        .add(MoshiResultTypeAdapterFactory(this.getEnvelopeHandler()))
        .addLast(KotlinJsonAdapterFactory())
        .build()


    private fun getOkHttpClient(): OkHttpClient {
        val okHttpClientBuilder = OkHttpClient.Builder()
        okHttpClientBuilder.addInterceptor(CommonRequestInterceptor(iNetworkRequiredInfo))
        okHttpClientBuilder.addInterceptor(CommonResponseInterceptor())

        handlerBuilder(okHttpClientBuilder)

        getInterceptor()?.let {
            okHttpClientBuilder.addInterceptor(it)
        }


        if (iNetworkRequiredInfo != null && iNetworkRequiredInfo!!.isDebug()) {
            val httpLoggingInterceptor = HttpLoggingInterceptor()
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
            okHttpClientBuilder.addInterceptor(httpLoggingInterceptor)
        } else {
            // throw exception
        }
        return okHttpClientBuilder.build()
    }


    open fun <T> getService(service: Class<T>?): T {
        return mRetrofit.create(service)
    }


    /**
     * 中间参数添加，可通过重写实现
     */
    protected open fun handlerBuilder(builder:OkHttpClient.Builder){
        val sslParams : SSLSocketClient.SSLParams?  =SSLSocketClient.getSslSocketFactory()
        sslParams?.let {
            builder.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
        }
    }


    protected abstract fun getInterceptor(): Interceptor?

    protected open fun getEnvelopeHandler(): Envelope? {
        return null
    }
}